<template>
    <div>
        <PageTitle :title="form.id ? '编辑优惠券' : '新增优惠券'"></PageTitle>
        <Form ref="form" :model="form" :rules="rules" :label-width="100">
            <FormItem label="名称" prop="name">
                <Input v-model="form.name" style="width: 260px;" />
            </FormItem>
            <Row :gutter="20">
                <Col span="10">
                <FormItem label="描述" prop="description">
                    <Input v-model="form.description" type="textarea" :rows="4" placeholder="请输入优惠券描述" style="width: 300px;"></Input>
                </FormItem>
                </Col>
            </Row>
            <FormItem label="使用范围" prop="scope" required>
                <RadioGroup v-model="form.scope" type="button">
                    <Radio :label="1">全场通用</Radio>
                    <Radio :label="2">指定项目</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="类型" prop="type" required>
                <RadioGroup v-model="form.type" type="button">
                    <Radio :label="1">满减券</Radio>
                    <Radio :label="2">折扣券</Radio>
                    <Radio :label="3">代金券</Radio>
                </RadioGroup>
            </FormItem>
            <Row :gutter="20">
                <Col span="10">
                    <FormItem :label="form.type == 2 ? '折扣' : '面额'" prop="scale">
                        <InputNumber style="width:100px" v-model="form.scale" :min="0" :precision="2" :active-change="false"></InputNumber>
                    </FormItem>
                </Col>
                <Col span="14" style="margin-top: 5px; color: #ccc">
                    <div v-if="form.type == 2">请输入优惠券折扣，如8.5就是85折</div>
                    <div v-else>请输入优惠券面额，必须为正整数，且金额大于0</div>
                </Col>
            </Row>
            <FormItem label="使用条件" prop="amount_limit" required>
                <RadioGroup v-model="form.amount_limit">
                    <Radio :label="0">无限制</Radio>
                    <Radio :label="1">限制金额</Radio>
                </RadioGroup>
            </FormItem>
            <Row :gutter="20" v-if="form.amount_limit == 1">
                <Col span="10">
                    <FormItem label="限制金额" prop="amount">
                        <InputNumber v-model="form.amount" :min="0" :precision="2" :active-change="false" style="width: 300px"></InputNumber>
                    </FormItem>
                </Col>
                <Col span="14">
                    <div style="margin-top: 5px; color: #ccc">订单金额满多少元可用</div>
                </Col>
            </Row>
            <FormItem label="有效期类型" prop="indate_type" required>
                <RadioGroup v-model="form.indate_type">
                    <Radio :label="1">固定时间</Radio>
                    <Radio :label="2">领取后有效天数</Radio>
                </RadioGroup>
            </FormItem>
            <Row :gutter="20" v-if="form.indate_type == 2">
                <Col span="10">
                    <FormItem label="有效期设置" prop="indate_days">
                        <InputNumber v-model="form.indate_days" :min="1" :precision="0" :active-change="false" style="width: 270px;"></InputNumber>
                        <span style="margin-left: 10px;">天</span>
                    </FormItem>
                </Col>
                <Col span="14">
                    <div style="margin-top: 5px; color: #ccc">
                        请输入优惠券有效期，领取后N天有效
                    </div>
                </Col>
            </Row>
            <Row :gutter="20" v-if="form.indate_type == 1">
                <Col span="10">
                    <FormItem label="有效期设置" prop="times">
                        <DatePicker type="datetimerange" v-model="form.times" placement="bottom-end" :editable="false"
                        transfer placeholder="请选择有效期设置" style="width: 300px" :options="disableDateOptions"
                        @on-change='handleChangeTime'></DatePicker>
                    </FormItem>
                </Col>
                <Col span="14">
                    <div style="margin-top: 5px; color: #ccc">
                        请选择优惠券生效日期及到期日期
                    </div>
                </Col>
            </Row>
            <FormItem label="领取限制" prop="get_limit" required>
                <RadioGroup v-model="form.get_limit">
                    <Radio :label="0">无限制</Radio>
                    <Radio :label="1">限制数量</Radio>
                </RadioGroup>
            </FormItem>
            <Row :gutter="20" v-if="form.get_limit == 1">
                <Col span="10">
                    <FormItem label="限制数量" prop="get_number">
                        <InputNumber v-model="form.get_number" :min="1" :precision="0" :active-change="false" style="width: 300px;"></InputNumber>
                    </FormItem>
                </Col>
                <Col span="14">
                    <div style="margin-top: 5px; color: #ccc">
                        单个用户限制领取数量
                    </div>
                </Col>
            </Row>
            <FormItem label="发放总量" prop="total">
                <InputNumber v-model="form.total" :min="1" :precision="0" :active-change="false" style="width: 300px;"></InputNumber>
            </FormItem>
            <FormItem label="用户可见" prop="is_show" required>
                <RadioGroup v-model="form.is_show">
                    <Radio :label="1">显示</Radio>
                    <Radio :label="0">隐藏</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="状态" prop="state" required>
                <RadioGroup v-model="form.state">
                    <Radio :label="1">启用</Radio>
                    <Radio :label="-1">禁用</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="关联项目" v-if="form.scope == 2" required>
                <Button type="info" @click="handleOpenModal">选择项目</Button>
                <div style="margin-top: 10px;">
                    <Table border :columns="columns" :data="selectedProject"></Table>
                </div>
            </FormItem>
            <FormItem>
                <Button type="primary" :loading="submiting" @click="handleSubmit">提交</Button>
                <Button :disabled="submiting" @click="handleCancel" style="margin-left: 10px;">返回</Button>
            </FormItem>
        </Form>
        <Modal v-model="showModal" title="选择项目" width="1200px" @on-cancel="handleCancelSelect">
            <ProjectSelect ref="projectModal" multiple :value="selectedProject"></ProjectSelect>
            <div slot="footer">
                <Button @click="handleCancelSelect">取消</Button>
                <Button type="primary" @click="handleSelect">提交</Button>
            </div>
        </Modal>
        <Spin size="large" fix v-if="isLoading"></Spin>
    </div>
</template>

<script>
import TableRows from '@/components/utils/table-rows.vue';
import ProjectSelect from '@/components/selector/project-select.vue';
export default {
    components: {
        TableRows,
        ProjectSelect
    },
    data() {
        return {
            submiting: false,
            isLoading: false,
            showModal: false,
            selectedProject: [],
            form: {
                id: '',
                name: '',
                description: '',
                type: 1,
                scale: null,
                scope: 1,
                amount_limit: 0,
                amount: null,
                indate_type: 1,
                indate_stime: "",
                indate_etime: "",
                indate_days: null,
                get_limit: 0,
                get_number: null,
                total: null,
                state: 1,
                is_show: 1,
                times: []
            },
            disableDateOptions: {
                disabledDate(date) {
                    return date && date.valueOf() < Date.now() - 86400000;
                }
            },
            rules: {
                name: [{
                    required: true,
                    message: '请输入优惠券名称',
                    trigger: 'blur'
                }],
                scale: [{
                    required: true,
                    type: 'number',
                    message: "请填写面额|折扣",
                    trigger: 'blur'
                }, ],
                amount: [{
                    required: true,
                    type: 'number',
                    message: '请填写限制金额',
                    trigger: 'blur'
                }],
                get_number: [{
                    required: true,
                    type: 'number',
                    message: '请填写领取限制数量',
                    trigger: 'blur'
                }],
                total: [{
                    required: true,
                    type: 'number',
                    message: "请填写发放总量",
                    trigger: 'blur'
                }, ],
                indate_days: [{
                    required: true,
                    type: 'number',
                    message: '请输入有效期',
                    trigger: 'blur'
                }],
                times: [{
                    required: true,
                    type: 'array',
                    message: '请选择有效期',
                    trigger: 'change'
                }]
            },
            columns: [
                {
                    title: '基本信息',
                    minWidth: 250,
                    render: (h, params) => {
                        return h(TableRows, {
                            props: {
                                src: params.row.img || '/static/images/default_avatar.png'
                            }
                        }, [
                            h('p',params.row.name),
                            h('p',[
                                h('span',{style:{color:'green'}}, params.row.category ? '#'+params.row.category.name : ''),
                                h('span',{style:{color:'red',marginLeft:'5px'}},params.row.tour ? '#'+params.row.tour.name : '')
                            ])
                        ])
                    }
                },
                {
                    title: '票面价',
                    minWidth: 50,
                    render: (h, params) => {
                        return h("span", {}, params.row.min_price +'起');
                    }
                },
                {
                    title: '服务商价',
                    minWidth: 50,
                    render: (h, params) => {
                        return h("span", {}, params.row.partner_min_price +'起');
                    }
                },
                {
                    title: '库存',
                    maxWidth: 80,
                    key: 'stocks'
                },
                {
                    title: '已售',
                    maxWidth: 80,
                    key: 'sales'
                },
                {
                    title: '演出时间',
                    minWidth: 100,
                    render: (h, params) => {
                        return h('div', [
                            h('p',params.row.show_start_at + '至'), 
                            h('p',params.row.show_end_at)
                        ])
                    }
                },
                {
                    title: '上架状态',
                    width: 84,
                    align: 'center',
                    render: (h, params) => {
                        return h('span', params.row.shelf_status == 1 ? '上架' : '下架');
                    }
                },
                {
                    title: '操作',
                    render: (h, params) => {
                        return h('Button', {
                            props: {
                                size: 'small',
                                type: 'error'
                            },
                            on: {
                                click: () => {
                                    this.selectedProject.splice(params.index, 1);
                                }
                            }
                        }, '删除');
                    }
                }
            ]
        }
    },
    mounted() {
        if (this.$route.query.id) {
            this.form.id = this.$route.query.id;
            this.handleGetDetail();
        }
    },
    methods: {
        // 时间选择
        handleChangeTime(data) {
            this.form.times = data;
            if (this.form.times[0]) {
                this.form.indate_stime = this.form.times[0];
                this.form.indate_etime = this.form.times[1];
            } else {
                this.form.indate_stime = "";
                this.form.indate_etime = "";
            }
        },
        handleGetDetail() {
            this.isLoading = true;
            this.$ajax.get('/market/coupon/read/'+this.form.id).then(res => {
                this.form.name = res.name;
                this.form.description = res.description;
                this.form.type = res.type;
                this.form.scale = Number(res.scale);
                this.form.scope = res.scope;
                this.form.amount_limit = res.amount_limit;
                this.form.amount = res.amount ? Number(res.amount) : null;
                this.form.indate_type = res.indate_type;
                this.form.indate_days = res.indate_days;
                this.form.indate_stime = res.indate_stime;
                this.form.indate_etime = res.indate_etime;
                this.form.times = [res.indate_stime, res.indate_etime];
                this.form.get_limit = res.get_limit;
                this.form.get_number = res.get_number;
                this.form.total = res.total;
                this.form.state = res.state;
                this.form.is_show = res.is_show;
                this.selectedProject = res.projectInfo ? res.projectInfo : [];
                this.isLoading = false;
            }).catch(err => {
                this.$Message.error(err.message || '加载失败');
            })
        },
        handleOpenModal() {
            this.$refs.projectModal.init();
            this.showModal = true;
        },
        handleSelect() {
            let res = this.$refs.projectModal.getCheckeds();
            res.map(item => {
                this.selectedProject.push(item);
            })
            this.handleCancelSelect();
        },
        handleCancelSelect() {
            this.$refs.projectModal.clear();
            this.showModal = false;
        },
        handleSubmit() {
            if (this.submiting) return false;
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const { form, selectedProject } = this;
                    const project_ids = selectedProject.map(item => item.id);
                    // 验证项目
                    if (form.scope === 2 && project_ids.length === 0) {
                        this.$Message.error('请选择项目');
                        return false;
                    }
                    let params = {
                        name: form.name,
                        description: form.description,
                        type: form.type,
                        scale: form.scale,
                        scope: form.scope,
                        amount_limit: form.amount_limit,
                        indate_type: form.indate_type,
                        get_limit: form.get_limit,
                        total: form.total,
                        state: form.state,
                        is_show: form.is_show
                    };
                    // 有效期
                    if(form.indate_type === 2) {
                        params.indate_days = form.indate_days;
                    }else{
                        params.indate_stime = form.indate_stime;
                        params.indate_etime = form.indate_etime
                    }
                    // 使用条件
                    if(form.amount_limit === 1) {
                        params.amount = form.amount;
                    }
                    // 指定项目
                    if(form.scope === 2) {
                        params.project_ids = project_ids.join(',');
                    }
                    // 限制数量
                    if(form.get_limit === 1) {
                        params.get_number = form.get_number;
                    }
                    if (form.id) {
                        this.$ajax.put('/market/coupon/update/'+form.id, params).then(res => {
                            this.$Message.success('编辑成功');
                            this.handleCancel();
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }else{
                        this.$ajax.post('/market/coupon/save', params).then(res => {
                            this.$Message.success('添加成功');
                            this.handleCancel();
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }
                }
            })
        },
        handleCancel() {
            this.$router.back();
        }
    }
}
</script>